from DrissionPage import ChromiumPage, ChromiumOptions
import time
import os

def get_name(y, m, d2):
    co = ChromiumOptions().set_paths(browser_path=r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe") # 设置浏览器路径
    # co.set_argument('--headless')  # 设置为无头模式

    page = ChromiumPage(co)  # 创建浏览器对象
    page.get(f'https://www.imdb.com/search/title/?release_date={y}-{m}-1,{y}-{m}-{d2}&countries=US')

    page.wait(3)  # 等待页面加载完全
    page.run_js("window.scrollTo(0, 0);")  # 先滚动到顶部
    page.wait(1)
    urls = []

    # 点击“更多”按钮
    for i in range(2):
        more_button = page.ele('x://span[@class="ipc-see-more__text"]')
        more_button.click()
        page.wait(3)

    first_element = page.ele('x://div[@class="ipc-page-grid__item ipc-page-grid__item--span-2"]')
    print(first_element)

    # 获取该元素中的所有次级元素
    if first_element:
        page.wait(5)
        lis = first_element.eles('x://li[@class="ipc-metadata-list-summary-item"]')
        # print(len(lis))
        for li in lis:
            text = li.ele('x://span[@class="sc-d5ea4b9d-1 cVWRWO"]').text.strip()
            if "Series" not in text:
                # print(text)
                movie_name = li.ele('x://h3[@class="ipc-title__text"]').text
                # 取.后面的文字并去掉前后空格
                movie_name = movie_name.split('.')[1].strip()
                encoded_movie_name = movie_name.replace(" ", "%20")
                link = f'https://subdl.com/search/{encoded_movie_name}'
                # print(link)
                urls.append(link)

    # 将urls写入文件
    with open(rf"D:\subtitle\moves\{y}\{m}月\urls.txt", 'w', encoding='utf-8') as file:
        for url in urls:
            file.write(url + '\n')  # 将每个 URL 写入文件，每行一个

    page.quit()
    print("已写入文件")


def get_subtitle(y, m):
    with open(rf"D:\subtitle\moves\{y}\{m}月\urls.txt", 'r', encoding='utf-8') as file:
        urls = [line.strip() for line in file]

    co1 = ChromiumOptions().set_paths(browser_path=r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe") # 设置浏览器路径

    co1.set_pref('download.default_directory', fr'D:\subtitle\moves\{y}\{m}月')  # 指定下载路径

    page1 = ChromiumPage(co1)  # 创建浏览器对象

    num = 0                 # 追踪下载成功次数

    for href in urls:
        time.sleep(3)
        page1.get(href)
        success = False     # 追踪是否下载成功

        try:
            button = page1.eles('x://div[@class="flex flex-col gap-1"]')
            if not button:
                print(f"{href}没有字幕")
                continue  # 没有找到任何字幕选项，跳到下一个URL

            b_num = 0
            for b in button:
                page1.wait(1)

                # movie
                div = b.ele('x://div[@class="flex gap-2 align-middle"]')
                lines = div.text.split('\n')
                # print(lines)

                # 年代
                h3 = b.ele('x://h3[@class="text-sm  md:text-lg"]')
                text_y = h3.text.split('(')[1].strip(')')
                # print(text_y)

                b_num += 1
                if b_num == len(button):
                    if lines[0] != "movie" or text_y != str(y):
                        print("没有符合条件的字幕")
                print(lines[0], text_y,y)

                if lines[0] == "movie" and text_y == str(y):
                    # print(f"点击")
                    # print(div)
                    div.click()
                    page1.wait(1)
                    time.sleep(1)

                    selects = page1.eles('x://div[@class="flex flex-col mt-4 select-none"]')
                    if not selects:
                        print(f"{href}没有可选字幕")
                        break

                    for s in selects:
                        s_text = s.text.split('\n')
                        # print(s_text[0])
                        if s_text[0] == "EN":
                            li = s.eles('x://div[@class="flex-shrink-0 flex-grow-0 inline-flex items-center gap-2"]')
                            # print(li[0])
                            li[0].click()
                            time.sleep(2)
                            num += 1
                            print(f"{href}下载成功,第{num}次")
                            page1.wait(2)
                            success = True
                            break

                    if not success:
                        print(f"{href}没有英文字幕")
                    break

        except Exception as e:
            pass

    print(f"下载完成,共成功下载 {num} 次")
    page1.quit()


y = 2020
m = 6
d2 = 30

# get_name(y, m, d2)
get_subtitle(y, m)